from option import Option
import signals
import stats
import helpers
import gtk
import re
from helpers import fmt, unfmt

period = resolution = type = type_clause = treeview = False
def populate(data):
	global treeview
	
	cur = stats.CONN.cursor()

	model = treeview.get_model()

	model.clear()

	model.append(None, (_('Number of solves'), str(len(data))))

	if not data:
		return

	model.append(None, (_('Best time'), fmt(min(data)[0])))
	model.append(None, (_('Worst time'), fmt( max(data )[0]) ))
	# Distribution

	rows = map(lambda x: x[0], data)
	buckets_10 = [0]*(int(max(rows))/10+1)
	buckets_1 = [0]*((int(max(rows))+11))
	for row in rows:
		buckets_1[int(row)] += 1
		buckets_10[int(row)/10] += 1

	parent = model.append(None, (_('Score distribution'),''))

	for i10 in xrange(0,len(buckets_10)):
		parent_10 = model.append(parent,
				(''.join([
					str(i10*10),
					'-',
					str(i10*10+10),
					's']),
					''.join([
						str(buckets_10[i10]),
						' (',
						str(round(buckets_10[i10]*100/float(len(rows)),2)),
						'%)'])))
		for i1 in xrange(i10*10,i10*10+10):
			model.append(parent_10, (''.join(
				[str(i1),
					'-',
					str(i1+1),
					's']),
				''.join([str(buckets_1[i1]),
					' (',
						str(round(buckets_1[i1]*100/float(len(rows)),2)),

						' %)']
					)))

def on_apply_clicked(widget, type, resolution, period):
	populate(helpers.processPeriodSelection(type, resolution, period))

def init():
	global treeview
	vbox = gtk.VBox()
	vbox.set_border_width(12)
	vbox.set_spacing(6)

	treeview = gtk.TreeView()
	scroll = gtk.ScrolledWindow()
	scroll.set_property('hscrollbar-policy',gtk.POLICY_NEVER)
	scroll.add(treeview)
	vbox.pack_end(scroll)

	tree = gtk.TreeStore(str, str)

	treeview.set_model(tree)

	nameCol = gtk.TreeViewColumn(_('Name'))
	valueCol = gtk.TreeViewColumn(_('Value'))

	treeview.append_column(nameCol)
	treeview.append_column(valueCol)

	nameCell = gtk.CellRendererText()
	nameCol.pack_start(nameCell, True)
	nameCol.add_attribute(nameCell, 'text',0)

	valueCell = gtk.CellRendererText()
	valueCol.pack_start(valueCell, True)
	valueCol.add_attribute(valueCell, 'text',1)

	hbox = gtk.HBox()

	hbox.set_spacing(6)

	type, resolution, period = helpers.createPeriodSelection()

	hbox.pack_start(type)
	hbox.pack_start(resolution)
	hbox.pack_start(period)

	butt = gtk.Button(gtk.STOCK_APPLY)
	butt.set_use_stock(True)
	butt.connect('clicked',on_apply_clicked, type, resolution, period)

	hbox.pack_start(butt)

	vbox.pack_end(hbox, expand = False)

	vbox.show_all()

	Option().windowMain.stats.append_page(vbox)
	Option().windowMain.stats.set_tab_label_text(vbox,_('Advanced'))


def info():
	return {'name':'mod_stats',
			'author':'Michal Hordecki',
			'description':'Various stats for Cube Assistant.',
			}

def teardown():
	pass

